package com.hfi.security.core.social.weixin.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author ChangLiang
 * @date 2019/8/23
 */
public class WeixinImpl extends AbstractOAuth2ApiBinding implements Weixin {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?openid=%s&access_token=%s";

    private ObjectMapper objectMapper = new ObjectMapper();

    private String accessToken;

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public WeixinImpl(String accessToken) {
        /// 不知道为什么 不生效 在OAuth2TokenParameterRequestInterceptor中应该加上access_token=xxx
        // AbstractOAuth2ApiBinding 会自动帮我们处理query parameter named "access_token" 无需我们处理
        // super(accessToken, TokenStrategy.OAUTH_TOKEN_PARAMETER);
        this.accessToken = accessToken;
    }

    /**
     * 默认注册的StringHttpMessageConverter字符集是ISO-8859-1
     * 而微信返回的是UTF-8
     * 所以覆盖了原方法
     * @return
     */
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }

    @Override
    public WeixinUserInfo getUserInfo(String openId) {
        String url = String.format(URL_GET_USER_INFO, openId, accessToken);
        String response = getRestTemplate().getForObject(url, String.class);
        logger.info("获取到微信的用户信息:{}", response);
        if (StringUtils.contains(response, "errcode")) {
            return null;
        }
        WeixinUserInfo profile = null;
        try {
            profile = objectMapper.readValue(response, WeixinUserInfo.class);
        } catch (IOException e) {
            throw new RuntimeException("获取微信用户信息出错");
        }
        return profile;
    }
}
